#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
from django.db.models import Q
def data_filter(request, admin_class):
    '''组合过滤及排序'''
    conditions = {}
    orderby_key = None
    search_key = ''
    builtin_keys = ['page', 'o', '_q']    # 保留字段
    for k,v in request.GET.items():
        if k in builtin_keys:    # 保留的分页和排序关键字
            if k == 'o':
                orderby_key = v
            if k =='_q':
                search_key = v
            continue
        if v:
            conditions[k] = v
    q_obj = Q()
    q_obj.connector = 'OR'
    for column in admin_class.search_fields:
        q_obj.children.append(('%s__contains'%column[0], search_key))    # 添加搜索条件

    if orderby_key:    # 判断排序
        obj_list = admin_class.model.objects.filter(**conditions).filter(q_obj).order_by(orderby_key).all()
        if orderby_key.startswith('-'):
            orderby_key = orderby_key.strip('-')
        else:
            orderby_key = '-%s'%orderby_key
    else:
        default_orderby_key = '-%s'%admin_class.ordering if admin_class.ordering else '-id'    # 使用默认排序规则
        obj_list = admin_class.model.objects.filter(**conditions).filter(q_obj).order_by(default_orderby_key).all()
    return obj_list, conditions, orderby_key




